import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Form, Row, Col, Input, Button, Select, Radio, Checkbox, message } from 'antd';
import { LANGUAGE_OPTIONS, TYPE_MAP } from '../constants';
import axios from 'axios';
const { Option } = Select;

interface AddQuestionProps {
  title: string;
  initialValues?: any;
  isEdit?: boolean;
  questionId?: string;
}

const AddQuestion: React.FC<AddQuestionProps> = ({ title, initialValues, isEdit, questionId }) => {
  const [form] = Form.useForm();
  const typeValue = Form.useWatch('type', form);
  const isCode = typeValue === 'code';
  const isChoice = ['single', 'multi'].includes(typeValue || '');

  const [charCount, setCharCount] = useState(0);
  const [loading, setLoading] = useState(false);
  const inputValueRef = useRef('');

  const navigate = useNavigate(); //导航

  // 如果有初始值，设置表单值
  useEffect(() => {
    if (initialValues) {
      form.setFieldsValue(initialValues);
      if (initialValues.codeAnswer) {
        inputValueRef.current = initialValues.codeAnswer;
        setCharCount(initialValues.codeAnswer.length);
      }
    }
  }, [initialValues, form]);

  type FieldType = {
    type?: string;
    language?: string[];
    title?: string;
    codeAnswer?: string;
    a?: string;
    b?: string;
    c?: string;
    d?: string;
    answer?: string | string[]; // 支持数组
  };
  const requiredIfNotCode = (_: any, value: string | Array<string>) => {
    const type = form.getFieldValue('type');
    if (type === 'code') return Promise.resolve();

    if (!value || (Array.isArray(value) && value.length === 0)) {
      return Promise.reject(new Error('该选项不能为空'));
    }

    return Promise.resolve();
  };

  const onFinish = async (values: FieldType) => {
    try {
      setLoading(true);
      const answer = isChoice
        ? typeValue === 'multi'
          ? JSON.stringify(values.answer)
          : values.answer
        : values.codeAnswer;
      // 构建提交数据
      const submitData = {
        type: TYPE_MAP[values.type as keyof typeof TYPE_MAP],
        content: values.title,
        options: isChoice ? JSON.stringify([values.a, values.b, values.c, values.d]) : null,
        answer: answer,
        difficulty: 'medium',
        language: values.language ? values.language.join(',') : null
      };

      console.log('Submitting data:', submitData);

      let response;
      if (isEdit && questionId) {
        response = await axios.patch(`/api/questions/${questionId}`, submitData);
      } else {
        response = await axios.post('/api/questions', submitData);
      }

      console.log('Server response:', response.data);

      if (response.data.code === 0) {
        message.success(response.data.message || (isEdit ? '更新题目成功' : '添加题目成功'));
        form.resetFields();
        inputValueRef.current = '';
        setCharCount(0);
        navigate('../');
      } else {
        message.error(response.data.message || (isEdit ? '更新题目失败' : '添加题目失败'));
      }
    } catch (error) {
      console.error(isEdit ? '更新题目失败:' : '添加题目失败:', error);
      if (axios.isAxiosError(error)) {
        console.error('Error response:', error.response?.data);
      }
      message.error(isEdit ? '更新题目失败，请重试' : '添加题目失败，请重试');
    } finally {
      setLoading(false);
    }
  };
  const handleCancel = () => {
    form.resetFields();
    inputValueRef.current = '';
    setCharCount(0);
    navigate('../');
  };

  return (
    <Card title={title} style={{margin:10,marginRight:5}}>
      <Form name="basic" form={form} onFinish={onFinish}>
        <Row gutter={24}>
          <Col span={9}>
            <Form.Item<FieldType>
              label="类型"
              name="type"
              rules={[{ required: true, message: '类型不能为空!' }]}
            >
              <Select placeholder="请选择题目类型" allowClear style={{ width: '100%' }}>
                <Option value="single">单选题</Option>
                <Option value="multi">多选题</Option>
                <Option value="code">编程题</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={15}>
            <Form.Item<FieldType> label="语言" name="language">
              <Select
                mode="multiple"
                style={{ width: '100%' }}
                placeholder="请选择语言"
                options={LANGUAGE_OPTIONS}
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item<FieldType>
          label="标题"
          name="title"
          rules={[{ required: true, message: '标题不能为空!' }]}
        >
          <Input placeholder="请输入标题" />
        </Form.Item>
        <Form.Item
          style={{ marginBottom: 0 }}
          label={
            typeValue === 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>内容
              </span>
            ) : (
              '内容'
            )
          }
          name="codeAnswer"
          rules={[
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (getFieldValue('type') === 'code' && (!value || value.trim() === '')) {
                  console.log('Form values:', value);
                  return Promise.reject(new Error('编程题内容不能为空'));
                }
                return Promise.resolve();
              }
            })
          ]}
          extra={
            <span
              style={{
                display:'block',
                width: '100%',
                border: '1px solid #d9d9d9',
                borderTopWidth: 0,
                borderTopLeftRadius: 0,
                borderTopRightRadius: 0,
                borderBottomLeftRadius: 4,
                borderBottomRightRadius: 4,
                marginBottom:24
              }}
            >
              字符数：{charCount}
            </span>
          }
        >
          <Input.TextArea
            disabled={!isCode}
            onInput={(e: React.ChangeEvent<HTMLTextAreaElement>) => {
              const value = e.target.value;
              inputValueRef.current = value;
              setCharCount(value.length);
            }}
            allowClear
            style={{ borderBottomLeftRadius: 0, borderBottomRightRadius: 0, resize: 'none' }}
          />
        </Form.Item>
        <Form.Item<FieldType>
          label={
            typeValue !== 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>A
              </span>
            ) : (
              'A'
            )
          }
          name="a"
          rules={[{ validator: requiredIfNotCode }]}
        >
          <Input placeholder="请输入选项内容" disabled={!isChoice} allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label={
            typeValue !== 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>B
              </span>
            ) : (
              'B'
            )
          }
          name="b"
          rules={[{ validator: requiredIfNotCode }]}
        >
          <Input placeholder="请输入选项内容" disabled={!isChoice} allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label={
            typeValue !== 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>C
              </span>
            ) : (
              'C'
            )
          }
          name="c"
          rules={[{ validator: requiredIfNotCode }]}
        >
          <Input placeholder="请输入选项内容" disabled={!isChoice} allowClear />
        </Form.Item>
        <Form.Item<FieldType>
          label={
            typeValue !== 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>D
              </span>
            ) : (
              'D'
            )
          }
          name="d"
          rules={[{ validator: requiredIfNotCode }]}
        >
          <Input placeholder="请输入选项内容" disabled={!isChoice} allowClear />
        </Form.Item>

        <Form.Item
          label={
            typeValue !== 'code' ? (
              <span>
                <span style={{ color: 'red', marginRight: 4 }}>*</span>答案
              </span>
            ) : (
              '答案'
            )
          }
          name="answer"
          rules={[{ validator: requiredIfNotCode }]}
        >
          {isChoice ? (
            typeValue === 'single' ? (
              <Radio.Group disabled={!isChoice}>
                <Radio value="a">A</Radio>
                <Radio value="b">B</Radio>
                <Radio value="c">C</Radio>
                <Radio value="d">D</Radio>
              </Radio.Group>
            ) : (
              <Checkbox.Group
                options={[
                  { label: 'A', value: 'a' },
                  { label: 'B', value: 'b' },
                  { label: 'C', value: 'c' },
                  { label: 'D', value: 'd' }
                ]}
                disabled={!isChoice}
              />
            )
          ) : null}
        </Form.Item>
        <Form.Item label={null}>
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="default" style={{ marginRight: 10 }} onClick={handleCancel}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              确定
            </Button>
          </div>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default AddQuestion;
